package com.ibpd.shopping.web.controller.shopInterface;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.assist.UploadFile;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.entity.FavoriteEntity;
import com.ibpd.shopping.service.favorite.FavoriteServiceImpl;
import com.ibpd.shopping.service.favorite.IFavoriteService;
@Controller
public class Test  extends BaseController{
	@RequestMapping("test.do")
	public void test(Long id,String field,Integer value,HttpServletResponse resp,HttpServletRequest req) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		IFavoriteService favoriteService=(IFavoriteService) ServiceProxyFactory.getServiceProxy(FavoriteServiceImpl.class);
		List<FavoriteEntity> fl=favoriteService.getList();
		for(FavoriteEntity f:fl){
			favoriteService.deleteByPK(f.getId());
		}
		super.printMsg(resp, "0", "0", "ok");
	}
	@RequestMapping(value = "doUpload2.do")
    @ResponseBody
    public String processImageUpload(UploadFile file,HttpServletRequest request) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		String basePath = request.getRealPath("/uploadFiles/");
		File fbasePath = new File(basePath);
		if(!fbasePath.exists())
			fbasePath.mkdirs();
			factory.setRepository(fbasePath);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置单个文件的最大上传值
			upload.setFileSizeMax(1024*1024*100);
			// 设置整个request的最大值
			upload.setSizeMax(1024*1024*100*20);
			upload.setHeaderEncoding("UTF-8");
			
			try {
				List<?> items = upload.parseRequest(request);
				FileItem item = null;
				String fileName = null;
					item = (FileItem) items.get(0);
					String urlPath=request.getContextPath()+"/uploadFiles/"+item.getName();
					fileName = basePath + File.separator + item.getName();
					if (!item.isFormField() && item.getName().length() > 0)
						item.write(new File(fileName));
					String callback=request.getParameter("CKEditorFuncNum");
		            if(StringUtils.isNotBlank(callback)){
		                return "<script type='text/javascript'>"
		                + "window.parent.CKEDITOR.tools.callFunction(" + callback
		                + ",'" + urlPath + "',''" + ")"+"</script>";
		            }else{
		                return "{" + file.getUpload().getOriginalFilename() + "}!Success!";
		            }
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "failure";
	}
	@RequestMapping("getCpuId.do")
	public void getCpuId(HttpServletResponse resp,HttpServletRequest req) throws IOException{
		String osName=System.getProperty("os.name");
		
		String[] linux_getCpuId = {"/bin/sh", "-c", "dmidecode -t processor | grep ID"};
		String[] linux_getProductName = {"/bin/sh", "-c", "dmidecode -t system | grep 'Product Name'"};
		String[] linux_getDiskSerialNumber = {"/bin/sh", "-c", "hdparm -i /dev/sda |grep SerialNo"};
		List<String[]> lst=new ArrayList<String[]>();
		lst.add(linux_getCpuId);
		lst.add(linux_getDiskSerialNumber);
		lst.add(linux_getProductName);
		Map<String,String> m=new HashMap<String,String>();
		m.put("osName", osName);
		for(String[] s:lst){
			Process p=Runtime.getRuntime().exec(s);
			BufferedReader br = new BufferedReader(new InputStreamReader(p
	                .getInputStream()));
	        String inline; 
	        while ((inline = br.readLine()) != null) {
	        	IbpdLogger.getLogger(this.getClass()).info(inline);
	            if(s.equals(linux_getCpuId)){
	            	m.put("cpuId", inline.replace("ID:", "").replace(" ", "").replace("\t", ""));
	            }else if(s.equals(linux_getDiskSerialNumber)){
	            	String[] t=inline.split("SerialNo=");
	            	if(t.length==2)
	            		m.put("diskSerialNumber", t[1]);
	            	else
	            		m.put("diskSerialNumber","error");
	            }else if(s.equals(linux_getProductName)){
	            	m.put("productName", inline.replace("Product Name:", "").replace("\t", ""));
	            }else{
	            	m.put("other", inline);
	            }
	        }
	        br.close();		
		}
		JSONArray j=JSONArray.fromObject(m);
		super.printJsonData(resp, "\"rows\":"+j.toString()+"}");
	}
}
